// 导入Promise
import {
	request
} from '../../request/index.js'

Page({
	data: {
		//只能在页面wxml或者this.setData中使用
		goodsObj:{},
		isCollect:false
	},
	//js处理数据只能使用这个对象
	GoodList:{},
	onShow: function() {
		
		let pages = getCurrentPages()
		let currentPages = pages[pages.length - 1]
		let options = currentPages.options
		
		const {goods_id} = options
		this.getGoodsDetail(goods_id)
		
	},
	//获取商品的详情数据
	async getGoodsDetail(goods_id){
		const res = await request({
			url:"/goods/detail",
			data:{goods_id}
		})
		this.GoodList = res.data.message
		// 获取缓存中的商品收藏
		let collect = wx.getStorageSync("collect") || []
		// 判断当前商品是否被收藏
		let isCollect = collect.some(item => item.goods_id === this.GoodList.goods_id)
		this.setData({
			goodsObj:{
				pics:res.data.message.pics,
				goods_name:res.data.message.goods_name,
				goods_price:res.data.message.goods_price,
				goods_introduce:res.data.message.goods_introduce.replace(/\.webp/g,'.jpg')
			},
			isCollect
		})
		// console.log(this.GoodList);
	},
	
	//绑定点击事件
	handlePrevewImage(e){
		const urls = this.GoodList.pics.map( item => item.pics_mid );
		// console.log(e);
		//点击谁显示谁
		const current = e.currentTarget.dataset.url
		wx.previewImage({
			current,
			urls
		})
	},
	// 添加购物车
	handleCartAdd(){
		// 获取缓存中的数据
		  let cart = wx.getStorageSync("cart") || []
		  // 判断商品是否存在购物车
		  let index = cart.findIndex(item =>
		   item.goods_id === this.GoodList.goods_id
		  )
		  if(index === -1){
		   // 不存在添加元素
		   this.GoodList.num = 1
		   this.GoodList.checked = true
		   cart.push(this.GoodList)
		  }else{
		   // 存在 ++
		   cart[index].num++;
		  }
		  // 重新添加缓存
		  wx.setStorageSync("cart",cart)
		  // 弹窗提示用户
		  wx.showToast({
		   title:"添加成功",
		   icon:"success",
		   mask:true,
		   duration:1000
		  })	
	},
	handleCollect(){
		let isCollect = false
		let collect = wx.getStorageSync("collect") || []
		let index = collect.findIndex(item => item.goods_id === this.GoodList.goods_id)
		
		if(index!==-1){
			collect.splice(index,1)
			isCollect=true
			wx.showToast({
				title:'取消收藏',
				icon:'success',
				mask:true
			})
		}else{
			collect.push(this.GoodList)
			isCollect=false
			wx.showToast({
				title:'成功收藏',
				icon:'success',
				mask:true
			})
		}
		 
		wx.setStorageSync("collect",collect)
		this.setData({
			isCollect:!isCollect
		})
		
	}
})
